<?php
namespace app\admin\model;

class Analysis extends Base{

    protected $name = 'business_analysis';
    const STOCK_BASE_INFO = 'http://emweb.securities.eastmoney.com/PC_HSF10/BusinessAnalysis/PageAjax?code=';

    //经营数据-经营分析
    public function getStockBusinessAnalysis($val=[], $sid=0){

        $val['stock_code'] = trim($val['stock_code']);
        $reVal = 0;
        $reVal = $this->getUrl(self::STOCK_BASE_INFO.$val['jys'].$val['stock_code']);
        $reVal = json_decode($reVal,true);


        foreach($reVal['zygcfx'] AS $k=>$v){

            $data = [];
            $data['report_date'] = !empty($v['REPORT_DATE']) ? trim($v['REPORT_DATE']) : '' ;
            $data['item_name'] = !empty($v['ITEM_NAME']) ? trim($v['ITEM_NAME']) : '' ;
            $data['main_business_income'] = !empty($v['MAIN_BUSINESS_INCOME']) ? trim($v['MAIN_BUSINESS_INCOME']) : '' ;
            $data['mbi_ratio'] = !empty($v['MBI_RATIO']) ? trim($v['MBI_RATIO']) : '' ;
            $data['mbr_ratio'] = !empty($v['MBR_RATIO']) ? trim($v['MBR_RATIO']) : '' ;
            $data['mbc_ratio'] = !empty($v['MBC_RATIO']) ? trim($v['MBC_RATIO']) : '' ;
            $data['main_business_cost'] = !empty($v['MAIN_BUSINESS_COST']) ? trim($v['MAIN_BUSINESS_COST']) : '' ;
            $data['main_business_rpofit'] = !empty($v['MAIN_BUSINESS_RPOFIT']) ? trim($v['MAIN_BUSINESS_RPOFIT']) : '' ;
            $data['gross_rpofit_ratio'] = !empty($v['GROSS_RPOFIT_RATIO']) ? trim($v['GROSS_RPOFIT_RATIO']) : '' ;
            $data['rank'] = !empty($v['RANK']) ? trim($v['RANK']) : '' ;
            $data['year'] = date('Ymd',strtotime($data['report_date']));

            $reVal = $this->businessAnalysisIsExist($data, ['sid'=>$sid, 'stock_code'=>$val['stock_code']]);
        }
        return $reVal;
    }

    protected function businessAnalysisIsExist($val=[], $arr=[]){
        $reVal = [];
        $reVal = $this->where(['stock_code'=>$arr['stock_code'], 'sid'=>$arr['sid'],'report_date'=>$arr['report_date'],'year'=>$arr['year']])->find();
        if(!empty($reVal['bid'])){
            return $this->where(['bid'=>$reVal['bid']])->update($val);
        }else{
            $val['sid'] = $arr['sid'];
            $val['stock_code'] = $arr['stock_code'];
            return $reTmp = $this->insert($val);
        }
    }

    //删除
    public function delStockBusinessAnalysis($sid=0, $stock_code=''){
        $this->where(['sid'=>$sid,'stock_code'=>$stock_code])->delete();
    }

    //详情-经营分析
    public function detailStockBusinessAnalysis($sid=0, $stock_code=''){
        return $this->where(['sid'=>$sid,'stock_code'=>$stock_code])->order('report_date desc')->select();
    }
}